package fy.erp.controller;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fy.erp.bean.OrderContractBean;
import fy.erp.dao.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;

import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.controller.BaseController;
import com.seeyon.ctp.common.filemanager.manager.FileManager;

import fy.erp.bean.LingLiaoBean;
import fy.erp.bean.SalesContractBean;
import fy.erp.manager.KeMuDuanFileReader;
import fy.erp.reports.ReportsCreator;
import fy.hr.dao.MQPersonInfoDao;
import fy.util.MyUtil;

public class ERP2OAController extends BaseController {

	private static final String JSON = "fy_view/oa_erp/JSON";
	// 科目段变更表导入数据回写网页
	private static final String IMP_KE_MU = "fy_view/oa_erp/imp_ke_mu";

	private static final String QUERY_CUSTOMER_NAME = "fy_view/oa_erp/queryCustomerName/queryCustomerByCode";
	private static final String WRITE_CUSTOMER_NAME = "fy_view/oa_erp/queryCustomerName/writeCustomerInfo";
	private FileManager fileManager;

	// private static final String projectExpenseReportsAccess =
	// "fy_view/oa_erp/projectExpenseReportsAccess";
	private static Log log = LogFactory.getLog(ERP2OAController.class);

	public FileManager getFileManager() {
		return fileManager;
	}

	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}

	public ModelAndView queryOrderContract(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String number = request.getParameter("number");
		//String factory = request.getParameter("factory");
		ModelAndView mav = new ModelAndView(JSON);
		response.setCharacterEncoding("utf-8");
		if (MyUtil.strIsNotNull(number) //&& MyUtil.strIsNotNull(factory)
				&& AppContext.getCurrentUser() != null) {
			number = java.net.URLDecoder.decode(number, "utf-8");
			//factory = java.net.URLDecoder.decode(factory, "utf-8");

			log.info(new StringBuilder().append("查询计划订单打印报表（销售），计划单号：")
					.append(number));//.append("，生产工厂：").append(factory));

			QueryOrderContractDao dao = new QueryOrderContractDao();
			try {
				dao.query(number);

				OrderContractBean ocb = dao.getOrderContractBean();

				if (ocb != null) {
					mav.addObject("jsonStr", ocb.toString());
				} else {
					mav.addObject("jsonStr", "2");
				}

			} catch (Exception e) {
				log.error(new StringBuilder().append("查询计划订单打印报表（销售），计划单号：")
						.append(number), e);
				mav.addObject("jsonStr", "3");
			}

		} else {

			mav.addObject("jsonStr", "1");
		}

		return mav;
	}
	
	public ModelAndView querySalesContract(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String number = request.getParameter("number");
		String factory = request.getParameter("factory");
		ModelAndView mav = new ModelAndView(JSON);
		response.setCharacterEncoding("utf-8");
		if (MyUtil.strIsNotNull(number) && MyUtil.strIsNotNull(factory)
				&& AppContext.getCurrentUser() != null) {
			number = java.net.URLDecoder.decode(number, "utf-8");
			factory = java.net.URLDecoder.decode(factory, "utf-8");

			log.info(new StringBuilder().append("查询分工厂计划订单打印报表（销售），计划单号：")
					.append(number).append("，生产工厂：").append(factory));

			QuerySalesContractDao dao = new QuerySalesContractDao();
			try {
				dao.query(number, factory);

				SalesContractBean scb = dao.getSalesContractBean();

				if (scb != null) {
					mav.addObject("jsonStr", scb.toString());
				} else {
					mav.addObject("jsonStr", "2");
				}

			} catch (Exception e) {
				log.error(new StringBuilder().append("查询分工厂计划订单打印报表（销售），计划单号：")
						.append(number).append("，生产工厂：").append(factory), e);
				mav.addObject("jsonStr", "3");
			}

		} else {

			mav.addObject("jsonStr", "1");
		}

		return mav;
	}

	public ModelAndView queryLingLiaoFaLiao(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String number = request.getParameter("number");
		String org_id = request.getParameter("org_id");
		ModelAndView mav = new ModelAndView(JSON);
		response.setCharacterEncoding("utf-8");

		if (MyUtil.strIsNotNull(number) && AppContext.getCurrentUser() != null) {
			number = java.net.URLDecoder.decode(number, "utf-8");

			log.info(new StringBuilder().append("查询领料发料单，ERP单据编号：").append(
					number));

			try {
				QueryLingLiaoFormDao dao = new QueryLingLiaoFormDao();
				dao.setNumber(number);
				dao.setOrg_id(org_id);
				if (dao.checkNumberIsNotExist() && dao.query()) {
					LingLiaoBean bean = dao.getLingLiaoBean();
					if (bean != null) {
						mav.addObject("jsonStr", bean.toString());
					} else {
						mav.addObject("jsonStr", "2");
					}
				} else {
					mav.addObject("jsonStr", new StringBuilder().append("4:")
							.append(dao.getErrorMessage()).toString());
				}

			} catch (Exception e) {
				log.error(
						new StringBuilder().append("查询领料发料单，ERP单据编号")
								.append(number).append("发生异常"), e);
				e.printStackTrace();
				mav.addObject("jsonStr", "3");
			}

		} else {

			mav.addObject("jsonStr", "1");
		}

		return mav;
	}

	// /**
	// * 获取项目费用报表授权界面
	// *
	// * @param request
	// * @param response
	// * @return
	// * @throws Exception
	// */
	// public ModelAndView getProjectExpenseReportsAccessJSP(
	// HttpServletRequest request, HttpServletResponse response)
	// throws Exception {
	// ModelAndView mav = new ModelAndView();
	// if ("group-admin".equals(AppContext.getCurrentUser().getLoginName())) {
	// mav.setViewName(projectExpenseReportsAccess);
	// }
	// return mav;
	// }
	/**
	 * 获取项目费用报表数据
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView queryCost(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView(JSON);
		response.setCharacterEncoding("utf-8");

		if (AppContext.getCurrentUser() != null) {
			String early = request.getParameter("early");
			String last = request.getParameter("last");
			QueryProjectCostDao dao = new QueryProjectCostDao();
			dao.setEarly(early);
			dao.setLast(last);
			dao.setNumber(request.getParameter("number"));

			String company = request.getParameter("company");

			if (company != null) {
				company = java.net.URLDecoder.decode(company, "utf-8");
			}
			dao.setCompanyName(company);

			dao.setAccountID(AppContext.getCurrentUser().getLoginAccount());

			if (dao.query()) {
				mav.addObject("jsonStr",
						"{success : true, data : " + dao.getResult() + "}");
			} else {

				mav.addObject("jsonStr",
						"{success : false, msg : '" + dao.getError() + "'}");
			}
		} else {
			mav.addObject("jsonStr", "{success : false, msg : '用户还未登陆'}");
		}
		return mav;
	}

	/**
	 * 获取处理ERP和OA交互的JSP界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getERP_OAJSP(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		User user = AppContext.getCurrentUser();
		if (user != null) {
			// IJspOperator o = JSPManager.createOperator(request
			// .getParameter("page"));
			// o.setUser(user);
			// o.setModelAndView(mav);
			// o.init();
		}
		return mav;
	}

	public ModelAndView querySubjectInfo(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView(JSON);
		response.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		User user = AppContext.getCurrentUser();
		if (user != null) {
			String field = request.getParameter("field");
			String operate = request.getParameter("operate");
			if (MyUtil.strIsNotNull(operate) && MyUtil.strIsNotNull(field)) {
				field = java.net.URLDecoder.decode(field, "utf-8");
				String reset = request.getParameter("reset");
				QuerySubjectInfoDao dao = new QuerySubjectInfoDao();
				dao.setField(field);
				dao.setOperate(operate);
				dao.setReset(reset);
				mav.addObject(
						"jsonStr",
						new StringBuilder().append("{success:")
								.append(dao.query()).append(", result:")
								.append(dao.getResult()).append("}").toString());
			} else
				mav.addObject("jsonStr", "2");
		} else
			mav.addObject("jsonStr", "1");
		return mav;
	}

	public ModelAndView getCompanyJSON(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView(JSON);
		response.setCharacterEncoding("utf-8");
		User user = AppContext.getCurrentUser();
		String operate = request.getParameter("operate");
		if ("1".equals(operate)) {
			if (user != null) {
				QueryKeMuDuanCompanyDao.query();
				mav.addObject("jsonStr",
						QueryKeMuDuanCompanyDao.getArrayResult());
			} else
				mav.addObject("jsonStr", "[]");
		} else {
			if (user != null) {
				mav.addObject("jsonStr", QueryKeMuDuanCompanyDao.query());
			} else
				mav.addObject("jsonStr", "1");
		}
		return mav;
	}

	public ModelAndView expendProjectExpenseReports(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView(JSON);
		response.setCharacterEncoding("utf-8");
		User user = AppContext.getCurrentUser();
		if (user != null) {

			String early = request.getParameter("early");
			String last = request.getParameter("last");
			QueryProjectCostDao dao = new QueryProjectCostDao();
			dao.setAccountID(user.getLoginAccount());
			dao.setEarly(early);
			dao.setLast(last);
			dao.setNumber(request.getParameter("number"));

			String company = request.getParameter("company");
			if (company != null) {
				company = java.net.URLDecoder.decode(company, "utf-8");
			}

			dao.setCompanyName(company);

			dao.setExpend(true);

			if (dao.query()) {
				response.setContentType("application/x-msdownload;charset='UTF-8'");
				response.setHeader(
						"Content-Disposition",
						"attachment;filename="
								+ URLEncoder.encode(("报表.xls"), "UTF-8"));
				ReportsCreator creator = new ReportsCreator();
				creator.setRowBeans(dao.getProjectCostBeans());
				creator.setOutputStream(response.getOutputStream());
				creator.write();

			} else {
				mav.addObject(
						"jsonStr",
						"<script type=\"text/javascript\">alert('"
								+ dao.getError()
								+ "'); window.close();</script>");
			}

			// String content = request.getParameter("content");

			// ReportsCreator creator = new ReportsCreator();
			// creator.setContent(content);
			// creator.setOutputStream(response.getOutputStream());
			// if (!creator.write()) {
			// mav.addObject("jsonStr",
			// "<script type=\"text/javascript\">alert('数据异常');</script>");
			// }
			// mav.addObject("jsonStr",
			// "<script type=\"text/javascript\">window.close();</script>");
		} else
			mav.addObject("jsonStr",
					"<script type=\"text/javascript\">alert('用户还未登陆'); window.close();</script>");
		return mav;
	}

	public ModelAndView impKeMuDuanBianGengBiao(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mav = null;
		User user = AppContext.getCurrentUser();
		if (user != null) {
			mav = new ModelAndView(IMP_KE_MU);

			KeMuDuanFileReader reader = new KeMuDuanFileReader();

			reader.read();

			mav.addObject("result", reader.getResult());

		} else {
			mav = new ModelAndView(JSON);
			mav.addObject("jsonStr",
					"<script type=\"text/javascript\">alert('用户还未登陆'); window.close();</script>");
		}

		return mav;
	}

	
	///新产品立项报告
	public ModelAndView queryCustomerNameJSP(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView modelAndView = null;
		if (AppContext.getCurrentUser() != null) {
			modelAndView = new ModelAndView(QUERY_CUSTOMER_NAME);
		}
		return modelAndView;
	}
	public ModelAndView writeCustomerNameJSP(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
	ModelAndView modelAndView = new ModelAndView(WRITE_CUSTOMER_NAME);
			try {
				boolean success = false;
		String customerCode = request.getParameter("customerCode");
				response.setCharacterEncoding("utf-8");
				if (AppContext.getCurrentUser() != null && customerCode != null && !"".equals(customerCode)) {
					customerCode = customerCode.replaceAll(".*([';]+|(--)+).*", " ");
				if (!"".equals(customerCode)) {
						String[] customerCodeArray = customerCode.split(",");
						if (customerCodeArray != null && customerCodeArray.length != 0) {
							QueryCustomerNameDao  qcdao=new QueryCustomerNameDao();
							qcdao.setCodes(customerCodeArray);
						modelAndView.addObject("CustomerInfoJSON",qcdao.queryCustomer(customerCode).toString());
							success = true;}
				//}	
				if (!success) {
					modelAndView.addObject("CustomerInfoJSON", "{}");
				}
				}}} catch (Exception e) {
				e.printStackTrace();
			}
			return modelAndView;		
					
}

	
}
